import { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Form, Switch, DatePicker, Input, Radio, Button, Slider, message, Modal } from 'antd';
import { history, useModel } from 'umi';
import moment from 'moment';
import _, { isEmpty, uniqBy } from 'lodash';
import { planEdit, planDetail, planEditValid } from '@/services/operate';
import useDetailType from '@/hooks/useDetailType';

import ChooseActivty from '../chooseActivty/index';
// import TableDnd from './TableDnd/index';
import styles from './style.less';

const formatter = (value?: number) => `${value}%`;

const marks = {
  0: '0%',
  10: '10%',
};

const { confirm } = Modal;

const PackageDatail: React.FC = () => {
  const { isModify, isRead, params } = useDetailType<any>();

  const [detailForm] = Form.useForm();
  const controlGroupTypeWatch = Form.useWatch('controlGroupType', detailForm);
  const cgusercodesuffixWatch = Form.useWatch('cgusercodesuffix', detailForm);
  const [step, setStep] = useState(1);
  const [btnLoading, setBtnLoading] = useState(false);
  const [activityData, setActivityData] = useState<any>([]);
  const { initialState, setInitialState } = useModel('@@initialState');

  const queryDatial = async () => {
    const { code, data } = await planDetail({ id: params.id });
    if (code === 200 && data) {
      setActivityData(data.activityList);
      detailForm.setFieldsValue({
        brandName: data.brandName,
        planName: data.planName,
        timeRange: [moment(data.startTime), moment(data.endTime)],
        controlGroupType: data.controlGroupType ? true : false,
        controlGroupPercent: Number(data.controlGroupPercent) || 0,
        cgusercodesuffix: data.cgusercodesuffix,
      });
    }
  };

  useEffect(() => {
    if (isModify || isRead) {
      queryDatial();
    } else {
      if (detailForm && initialState && initialState.calendarAddDate) {
        detailForm.setFieldsValue({
          timeRange: [moment(initialState.calendarAddDate), null],
        });
      }
    }
  }, []);

  const onChangeSlider = (newValue: number) => {
    // 从 00 到 99 中随机捞取 5 个不重复的数，并确保小于 10 的数字前面补一位 0
    const randomNumbers = _.sampleSize(_.range(1000), newValue * 10).map((number) => {
      if (number < 100 && number >= 10) {
        return `0${number}`;
      } else {
        return number < 10 ? `00${number}` : `${number}`;
      }
    });
    detailForm.setFieldValue('cgusercodesuffix', randomNumbers.join(','));
  };

  const toPageActivity = () => {
    setStep(2);
  };

  const handleReset = () => {
    detailForm.resetFields();
    setActivityData([]);
  };

  const handleSubmitFetch = async (values: any) => {
    const param: any = {
      brandName: values.brandName,
      planName: values.planName,
      activityIds: activityData.map((item: any) => item.activityId).join(','),
      startTime:
        values.timeRange && values.timeRange[0]
          ? moment(values.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
          : '',
      endTime:
        values.timeRange && values.timeRange[1]
          ? moment(values.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
          : '',
      controlGroupType: values.controlGroupType ? 1 : 0,
      controlGroupPercent: Number(values.controlGroupPercent) || 0,
      cgusercodesuffix: values.cgusercodesuffix,
    };
    if (isModify) {
      param.id = params.id;
    }
    setBtnLoading(true);
    // const { code } = await planEdit(param);
    // setBtnLoading(false);
    // if (code === 200) {
    //   message.success('保存成功');
    //   handleReset();
    //   history.push(`/operate/package/list`);
    // }
  };

  const handleSubmit = () => {
    detailForm.validateFields().then(async (values) => {
      // 验证通过，执行提交逻辑
      const param: any = {
        activityIds: activityData.map((item: any) => item.activityId).join(','),
        startTime:
          values.timeRange && values.timeRange[0]
            ? moment(values.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
            : '',
        endTime:
          values.timeRange && values.timeRange[1]
            ? moment(values.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
            : '',
      };
      if (isModify) {
        param.id = params.id;
      }
      // const { code, data } = await planEditValid(param);
      // if (code === 200 && data) {
      //   confirm({
      //     content: `${data.message || ''}，是否需要调整该计划的生效时间？`,
      //     async onOk() {},
      //     async onCancel() {
      //       handleSubmitFetch(values);
      //     },
      //     okText: '去调整',
      //     cancelText: '继续保存',
      //   });
      // } else {
      //   handleSubmitFetch(values);
      // }
    });
  };

  // 子组件传过来的修改父组件
  const changeActivity = (activitys: any[]) => {
    if (step === 1) {
      setActivityData(activitys);
    } else {
      setActivityData(uniqBy([...activityData, ...activitys], 'activityId'));
    }
  };

  return (
    <PageContainer>
      {step === 1 ? (
        <div className={styles['detail-body']}>
          <div className={styles['form-body']}>
            <Form
              labelCol={{ span: 4 }}
              form={detailForm}
              initialValues={{
                brandName: 'KFC',
                planName: '',
                activityIds: [],
                timeRange: [],
                controlGroupType: true,
                controlGroupPercent: 0,
                cgusercodesuffix: '',
              }}
            >
              <Form.Item label="品牌" name="brandName">
                <Radio.Group disabled={isRead}>
                  <Radio value={'KFC'}>KFC</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                label="计划名称"
                name="planName"
                rules={[
                  { required: true, message: '不得为空' },
                  {
                    max: 15,
                    message: '计划名称长度不得超过15字符',
                  },
                ]}
              >
                <Input style={{ width: 350 }} autoComplete="off" disabled={isRead} />
              </Form.Item>
              <Form.Item
                label="置顶活动ID"
                name="activityIds"
                rules={[
                  // { required: true, message: '不得为空' },
                  {
                    required: true,
                    validator: () => {
                      if (isEmpty(activityData)) {
                        return Promise.reject('不得为空');
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
              >
                <Button
                  style={{ marginRight: 16 }}
                  type="primary"
                  onClick={() => {
                    toPageActivity();
                  }}
                  disabled={isRead}
                >
                  选择活动
                </Button>
                <span style={{ fontSize: 12, color: '#bfbfbf' }}>（下方表格内活动可拖拽排序）</span>
                {/* <TableDnd
                  activityData={activityData}
                  changeActivity={changeActivity}
                  isRead={isRead}
                /> */}
              </Form.Item>
              <Form.Item
                label="计划生效时间"
                name="timeRange"
                rules={[
                  { required: true, message: '不得为空' },
                  {
                    validator: (record: any, value) => {
                      if (value && (!value[0] || !value[1])) {
                        return Promise.reject(new Error('不得为空'));
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
              >
                <DatePicker.RangePicker
                  style={{ width: 350 }}
                  showTime={{
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                  }}
                  disabled={isRead}
                  disabledDate={(current: any) => {
                    // Can not select days before today and today
                    return current && current < moment().startOf('day');
                  }}
                />
              </Form.Item>
              <Form.Item
                label="是否配置用户控制组"
                name="controlGroupType"
                valuePropName="checked"
                tooltip={null}
              >
                <Switch disabled={isRead} />
              </Form.Item>
              {controlGroupTypeWatch && (
                <>
                  <Form.Item
                    label="用户控制组"
                    name="controlGroupPercent"
                    tooltip="设置适用该置顶计划的用户组比例"
                  >
                    <Slider
                      style={{ width: 350 }}
                      min={0}
                      max={10}
                      step={0.1}
                      onChange={onChangeSlider}
                      tooltip={{
                        formatter,
                        open: true,
                        placement: 'bottom',
                      }}
                      marks={marks}
                      disabled={isRead}
                    />
                  </Form.Item>
                  <Form.Item label="规则使用用户尾号" name="cgusercodesuffix">
                    {/* <Input style={{ width: 500, height: 200 }} bordered={false} disabled={isRead} /> */}
                    <div
                      style={{
                        paddingTop: 2,
                        // width: 350,
                        height: 'auto',
                        wordWrap: 'break-word',
                        wordBreak: 'break-all',
                      }}
                    >
                      {cgusercodesuffixWatch || ''}
                    </div>
                  </Form.Item>
                </>
              )}
            </Form>
          </div>
          <div className={styles['btns-body']}>
            {!isRead && (
              <Button
                style={{ marginRight: 16 }}
                type="primary"
                onClick={() => {
                  handleReset();
                }}
              >
                重置
              </Button>
            )}
            <Button
              style={{ marginRight: 16 }}
              onClick={() => {
                handleReset();
                history.push(`/operate/package/list`);
              }}
            >
              返回
            </Button>
            {!isRead && (
              <Button
                style={{ marginRight: 16 }}
                type="primary"
                onClick={() => {
                  handleSubmit();
                }}
                loading={btnLoading}
              >
                提交
              </Button>
            )}
          </div>
        </div>
      ) : (
        <ChooseActivty
          back={() => {
            setStep(1);
          }}
          changeActivity={changeActivity}
          activityDataFather={activityData}
          step={step}
        />
      )}
    </PageContainer>
  );
};

export default PackageDatail;
